import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:h_flutter_119/api/Api.dart';
import 'package:h_flutter_119/http/httpUtils.dart';
import 'package:h_flutter_119/mixin/toast_mixin.dart';
import 'package:h_flutter_119/page/home/model/wan/BannerData.dart';
import 'package:h_flutter_119/page/home/model/wan/BannerEntity.dart';
import 'package:h_flutter_119/page/home/model/wan/article_entity.dart';
import 'package:h_flutter_119/route/route_utils.dart';

class WanHomePage extends StatefulWidget {
  WanHomePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _WanHomePageState();
}

class _WanHomePageState extends State<WanHomePage> with ToastMixin,AutomaticKeepAliveClientMixin{

  @override
  bool get wantKeepAlive => true;

  List<BannerData> _bannerData = [];
  List<ArticleDataData> _articlesData = [];
  int _page = 0;
  late EasyRefreshController _easyRefreshController;
  final SwiperController _swiperController = SwiperController();
  List<int> _collectIds = [];

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true
    );

    _getBannerData();
    _getHomeData();
  }

  @override
  void dispose() {
    super.dispose();
    _swiperController.dispose();
    _easyRefreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: EasyRefresh.builder(
        controller: _easyRefreshController,
        header: PhoenixHeader(
          skyColor: Theme.of(context).primaryColor,
          position: IndicatorPosition.locator,
          safeArea: false,
        ),
        footer: PhoenixFooter(
          skyColor: Theme.of(context).primaryColor,
          position: IndicatorPosition.locator,
        ),
        onRefresh: () {
          _page = 0;
          _getHomeData();

          _easyRefreshController.finishRefresh();
          _easyRefreshController.resetFooter();
        },
        onLoad: () {
          _page++;
          _getHomeData();

          _easyRefreshController.finishLoad();
        },
        childBuilder: (context, physics) {
          return CustomScrollView(
            physics: physics,
            slivers: [
              SliverAppBar(
                backgroundColor: Theme.of(context).primaryColor,
                expandedHeight: MediaQuery.of(context).size.width / 1.8 * 0.8 + 20,  // +20 是上下的padding值
                pinned: false,
                flexibleSpace: FlexibleSpaceBar(
                  background: _getBanner(),
                ),
              ),
              const HeaderLocator.sliver(),
              SliverList(
                  delegate: SliverChildBuilderDelegate((context, index) {
                return _articlesData.isEmpty?null:_Article(_articlesData[index]);
              }, childCount: _articlesData.length)),
              const FooterLocator.sliver(),
            ],
          );
        },
      ),
    );
  }

  Widget? _getBanner() {
    if(_bannerData.isEmpty) {
      return null;
    }
    return Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.width / 1.8 * 0.8,
      padding: const EdgeInsets.symmetric(vertical: 10),
      child: Swiper(
        itemCount: _bannerData.length,
        controller: _swiperController,
        loop: true,
        autoplay: true,
        autoplayDelay: 3000,
        //触发时是否停止播放
        autoplayDisableOnInteraction: true,
        duration: 600,
        //视图宽度，即显示的item的宽度屏占比
        viewportFraction: 0.8,
        //两侧item的缩放比
        scale: 0.9,
        onTap: (index){
          goWeb(context, _bannerData[index].url ?? "",title: _bannerData[index].desc ?? "");
        },
        itemBuilder: (context, index) {
          return Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10.w)),
                image: DecorationImage(
                    image: NetworkImage(_bannerData[index].imagePath ?? ""),
                    fit: BoxFit.fill)),
          );
        },
        pagination: const SwiperPagination(
            builder: DotSwiperPaginationBuilder(
                activeSize: 9,
                size: 9,
                color: Colors.grey,
                activeColor: Colors.blue)),
      ),
    );
  }

  void _getBannerData() async {
    try {
      var bannerResponse = await HttpUtils(baseUrl: Api.BASE_WAN_URL).get(Api.WAN_BANNER);
      var bannerMap = json.decode(bannerResponse.toString());
      var entity = BannerEntity.fromJson(bannerMap);
      setState(() {
        _bannerData = entity.data ?? [];
      });
    } catch (e) {
      showShortToast(e.toString());
    }
  }

  void _getHomeData() async {
    try{
      if (_page == 0) {
        _articlesData.clear();
      }
      var articleResponse = await HttpUtils(baseUrl: Api.BASE_WAN_URL).get('${Api.WAN_ARTICLE_LIST}$_page/json');
      var articelMap = json.decode(articleResponse.toString());
      var entity = ArticleEntity.fromJson(articelMap);
      setState(() {
        _articlesData.addAll(entity.data?.datas??[]);
      });
    }catch(e){
      showShortToast(e.toString());
    }
  }

  Widget _Article(ArticleDataData articlesData) {
    return GestureDetector(
      onTap: () => _onArticleTab(articlesData),
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 5),
        child: ListTile(
          leading: IconButton(
            icon: Icon(
                _collectIds.contains(articlesData.id) ? Icons.favorite : Icons.favorite_border),
            tooltip: '收藏',
            color: _collectIds.contains(articlesData.id) ? Colors.red : Colors.grey,
            onPressed: () {
              articlesData.collect = !articlesData.collect!;
              setState((){
                if(articlesData.collect == true){
                  _collectIds.add(articlesData.id??0);
                }else{
                  _collectIds.remove(articlesData.id);
                }
              });
              showShortToast(articlesData.collect ?? false ? '收藏成功' : "取消收藏成功");
            },
          ),
          title: Text(
            articlesData.title ?? "",
            style: TextStyle(
              fontSize: 25.sp,
              overflow: TextOverflow.ellipsis,
            ),
            maxLines: 2,
          ),
          subtitle: Padding(
            padding: EdgeInsets.only(top: 10),
            child: Row(
              children: [
                Flexible(
                    flex: 1,
                    child: Container(
                      padding: EdgeInsets.symmetric(vertical: 3.h,horizontal: 6.h),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(20.w)),
                          border: Border.all(
                              color: Theme.of(context).primaryColor,
                              width: 1.5)),
                      child: Text(articlesData.superChapterName??"",
                      style: TextStyle(
                        color: Theme.of(context).primaryColor,
                        fontSize: 20.sp,
                        overflow: TextOverflow.ellipsis
                      ),maxLines: 1,),
                    )
                ),
                const SizedBox(width: 10),
                Text(articlesData.author??"")
              ],
            ),
          ),
        ),
      ),
    );
  }

  _onArticleTab(ArticleDataData articlesData) {
    goWeb(context, articlesData.link ?? "",title: articlesData.title ?? "");
  }


}
